package com.aiti.lulian.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.lulian.dto.ProductAttrParamDto;
import com.aiti.lulian.dto.ProductAttrQueryParamDto;
import com.aiti.lulian.dto.ProductAttrTypeDto;
import com.aiti.lulian.entity.EnterpriseProductAttr;
import com.aiti.lulian.entity.EnterpriseProductAttrType;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.mapper.EnterpriseProductAttrMapper;
import com.aiti.lulian.mapper.EnterpriseProductAttrTypeMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseUserMapper;
import com.aiti.lulian.mapper.Product0428Mapper;
import com.aiti.lulian.service.IEnterpriseProductAttrService;
import com.aiti.lulian.service.IEnterpriseProductAttrTypeService;
import com.aiti.lulian.vo.ProductAttrTypeVo;
import com.aiti.lulian.vo.ProductAttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: 产品属性
 * auth fcb
 * date 2025-04-28 10:03
 **/
@Service
@Slf4j
public class EnterpriseProductAttrServiceImpl extends BaseSerivceImpl<EnterpriseProductAttrMapper, EnterpriseProductAttr> implements IEnterpriseProductAttrService {

    @Autowired
    private IEnterpriseProductAttrTypeService productAttrTypeService;
    @Autowired
    private EnterpriseProductAttrTypeMapper productAttrTypeMapper;
    @Autowired
    private Product0428Mapper product0428Mapper;
    @Autowired
    private LuLianEnterpriseUserMapper enterpriseUserMapper;

    /**
     * 保存产品属性和产品类型
     * @param dto
     * @param userId 用户id
     * @param username 用户名
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void saveProductAttr(ProductAttrParamDto dto, String userId, String username){
        // 1. 参数校验
        this.checkSaveParam(dto, userId, username);
        String baseId = IdUtil.simpleUUID();
        // 2. 保存产品属性
        EnterpriseProductAttr productAttr = new EnterpriseProductAttr();
        productAttr.setBaseId(baseId);
        productAttr.setEnterpriseId(dto.getEnterpriseId());
        productAttr.setAttrName(dto.getAttrName());
        productAttr.setBaseCreateBy(userId);
        productAttr.setBaseCreateName(username);
        productAttr.setBaseCreateTime(new Date());
        productAttr.setBaseUpdateBy(userId);
        productAttr.setBaseUpdateName(username);
        productAttr.setBaseUpdateTime(new Date());
        if(CollectionUtil.isNotEmpty(dto.getProductAttrTypeList())) {
            List<String> collect = dto.getProductAttrTypeList().stream().map(ProductAttrTypeDto::getTypeName).collect(Collectors.toList());
            productAttr.setAttrType(StrUtil.join(",", collect));
        }
        this.save(productAttr);
        if(CollectionUtil.isEmpty(dto.getProductAttrTypeList())) {
            return;
        }
        // 3. 保存产品类型
        this.saveAttrType(dto.getProductAttrTypeList(), baseId);
    }

    /**
     * 更新产品属性
     * @param dto
     * @param userId
     * @param username
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateProductAttr(ProductAttrParamDto dto, String userId, String username){
        // 1. 参数校验
        this.checkUpdateParam(dto, userId, username);
        // 判断要删除的类型是否挂接了商品
        if(CollectionUtil.isNotEmpty(dto.getRemoveAttrTypeIdList())) {
            Integer count = product0428Mapper.queryProductCountByAttrTypeIdList(dto.getRemoveAttrTypeIdList(), dto.getEnterpriseId());
            if(count > 0) {
                throw new BusinessException("要删除的属性类型挂接了产品，请先修改产品的属性类型");
            }
        }
        // 2. 保存产品属性
        EnterpriseProductAttr productAttr = new EnterpriseProductAttr();
        productAttr.setBaseId(dto.getBaseId());
        productAttr.setAttrName(dto.getAttrName());
        productAttr.setBaseUpdateBy(userId);
        productAttr.setBaseUpdateName(username);
        productAttr.setBaseUpdateTime(new Date());
        if(CollectionUtil.isNotEmpty(dto.getProductAttrTypeList())) {
            List<String> collect = dto.getProductAttrTypeList().stream().map(ProductAttrTypeDto::getTypeName).collect(Collectors.toList());
            productAttr.setAttrType(StrUtil.join(",", collect));
        }
        this.updateById(productAttr);
        if(CollectionUtil.isEmpty(dto.getProductAttrTypeList())) {
            return;
        }
        // 区分哪些是新增的，哪些是修改的
        List<ProductAttrTypeDto> productAttrTypeList = dto.getProductAttrTypeList();

        List<EnterpriseProductAttrType>  updateList = new ArrayList<>(10);
        List<EnterpriseProductAttrType>  savedList = new ArrayList<>(10);
        int sort = 1;
        for(ProductAttrTypeDto typeDto : productAttrTypeList) {
            EnterpriseProductAttrType typePo = new EnterpriseProductAttrType();
            typePo.setTypeName(typeDto.getTypeName());
            typePo.setProductAttrId(dto.getBaseId());
            typePo.setSort(sort);
            typePo.setAttrTypePic(typeDto.getAttrTypePic());
            sort++;
            if(StrUtil.isNotEmpty(typeDto.getBaseId())) {
                typePo.setBaseId(typeDto.getBaseId());
                updateList.add(typePo);
            }else {
                typePo.setBaseId(IdUtil.simpleUUID());
                savedList.add(typePo);
            }
        }
        if(CollectionUtil.isNotEmpty(savedList)) {
            productAttrTypeService.saveBatch(savedList);
        }
        if(CollectionUtil.isNotEmpty(updateList)) {
            productAttrTypeService.updateBatchById(updateList);
        }
        if(CollectionUtil.isNotEmpty(dto.getRemoveAttrTypeIdList())) {
            productAttrTypeService.removeByIds(dto.getRemoveAttrTypeIdList());
        }
    }

    /**
     * 删除产品属性。属性逻辑删除，类型物理删除
     * @param baseIdList
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void deleteProductAttr(List<String> baseIdList, String userId, String username) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        if(StrUtil.isEmpty(userId)) {
            throw new BusinessException("未获取到当前用户标识");
        }
        if(StrUtil.isEmpty(username)) {
            throw new BusinessException("未获取到当前用户名");
        }
        // 查询当前要删除的属性是否挂接了商品
        List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(CollectionUtil.isEmpty(enterpriseUserList)) {
            throw new BusinessException("当前用户未绑定企业");
        }
        if(enterpriseUserList.size() != 1){
            throw new BusinessException("用户和企业绑定关系异常");
        }
        LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);
        Integer count = product0428Mapper.queryProductCountByAttrIdList(baseIdList, luLianEnterpriseUser.getEnterpriseId());
        if(count > 0) {
            throw new BusinessException("当前属性已挂接产品，请先修改对应产品的属性");
        }
        this.baseMapper.deleteByBaseIdList(baseIdList, userId, username);
        productAttrTypeMapper.deleteByAttrIdList(baseIdList);
    }

    /**
     * 查询详情
     */
    @Override
    public ProductAttrVo getProductAttrById(String baseId) {
        if(StrUtil.isEmpty(baseId)) {
            throw new BusinessException("产品属性id不能为空");
        }
        EnterpriseProductAttr productAttr = this.getById(baseId);
        ProductAttrVo productAttrVo = new ProductAttrVo();
        productAttrVo.setBaseId(productAttr.getBaseId());
        productAttrVo.setEnterpriseId(productAttr.getEnterpriseId());
        productAttrVo.setAttrName(productAttr.getAttrName());
        productAttrVo.setAttrType(productAttr.getAttrType());

        productAttrVo.setProductAttrTypeList(productAttrTypeMapper.queryListByProductAttrId(baseId));
        return productAttrVo;
    }

    @Override
    public List<ProductAttrVo> getEnterpriseProductAttr(String enterpriseId) {
        if(StrUtil.isEmpty(enterpriseId)) {
            throw new BusinessException("企业id不能为空");
        }
        List<ProductAttrVo> attrList = this.baseMapper.queryListByEnterpriseId(enterpriseId);
        return attrList;
    }

    @Override
    public List<ProductAttrTypeVo> getAttrTypeList(String productAttrId) {
        if(StrUtil.isEmpty(productAttrId)) {
            throw new BusinessException("产品属性id不能为空");
        }
        List<ProductAttrTypeVo> attrTypeList = productAttrTypeMapper.queryListByProductAttrId(productAttrId);
        return attrTypeList;
    }

    private void saveAttrType(List<ProductAttrTypeDto> typeDtoList, String baseId) {
        List<EnterpriseProductAttrType> saveAttrTypeList = new ArrayList<>(20);
        int sort = 1;
        for(ProductAttrTypeDto typeDto : typeDtoList) {
            if(StrUtil.isEmpty(typeDto.getTypeName()) || StrUtil.isEmpty(typeDto.getAttrTypePic())) {
                throw new BusinessException("产品类型或产品主图不能为空");
            }
            EnterpriseProductAttrType attrType = new EnterpriseProductAttrType();
            attrType.setBaseId(IdUtil.simpleUUID());
            attrType.setProductAttrId(baseId);
            attrType.setTypeName(typeDto.getTypeName());
            attrType.setSort(sort);
            attrType.setAttrTypePic(typeDto.getAttrTypePic());
            sort++;
            saveAttrTypeList.add(attrType);
        }
        productAttrTypeService.saveBatch(saveAttrTypeList);
    }

    /**
     * 分页查询产品属性
     * @param dto
     * @return
     */
    public PageResult<ProductAttrVo> pageList(ProductAttrQueryParamDto dto) {
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(dto.getPageNum() == null || dto.getPageNum() < 1 || dto.getPageSize() == null || dto.getPageSize() < 1) {
            throw new BusinessException("分页参数错误");
        }
        Page<ProductAttrVo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<ProductAttrVo> list = this.baseMapper.pageList(page, dto);
        return new PageResult<>(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
    }

    private void checkSaveParam(ProductAttrParamDto dto, String userId, String username) {
        if(StrUtil.isEmpty(dto.getAttrName())) {
            throw new BusinessException("产品属性名称不能为空");
        }
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(StrUtil.isEmpty(userId)) {
            throw new BusinessException("未获取到当前用户标识");
        }
        if(StrUtil.isEmpty(username)) {
            throw new BusinessException("未获取到当前用户名");
        }
    }

    private void checkUpdateParam(ProductAttrParamDto dto, String userId, String username) {
        if(StrUtil.isEmpty(dto.getBaseId())) {
            throw new BusinessException("产品属性id不能为空");
        }
        if(StrUtil.isEmpty(dto.getAttrName())) {
            throw new BusinessException("产品属性名称不能为空");
        }
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(StrUtil.isEmpty(userId)) {
            throw new BusinessException("未获取到当前用户标识");
        }
        if(StrUtil.isEmpty(username)) {
            throw new BusinessException("未获取到当前用户名");
        }
    }

}
